<template>
  <div>
    <div ref="barChart" :style="{ width: '100%', height: '400px' }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'BarChart',
  data() {
    return {
      chartInstance: null,
      chartOption: {
        title: {
          text: '订单支付时间柱状图'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: []  // 动态填充支付时间（payissuetime）
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            data: [] // 动态填充订单数量（counts）
          }
        ]
      }
    };
  },
  mounted() {
    this.initChart();
    this.fetchData(); // 获取数据并更新图表
  },
  methods: {
    initChart() {
      this.chartInstance = echarts.init(this.$refs.barChart);
      this.chartInstance.setOption(this.chartOption);
      window.addEventListener('resize', this.handleResize);
    },
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    async fetchData() {
      try {
        const response = await axios.get('/orders/orderfrom/orderresponse'); // 请求后端数据
        if (response.data.code === 200) {
          const data = response.data.data;

          // 提取支付时间和数量
          const payissuetime = data.map(order => order.payissuetime);
          const counts = data.map(order => order.counts);

          // 更新图表配置
          this.chartOption.xAxis.data = payissuetime; // 更新X轴数据
          this.chartOption.series[0].data = counts;   // 更新Y轴数据

          // 重新设置图表
          this.chartInstance.setOption(this.chartOption);
        } else {
          console.error('Error fetching data:', response.data.msg);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
};
</script>

<style>
</style>
